package com.cc.util;

import com.github.tobato.fastdfs.domain.fdfs.MetaData;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.AppendFileStorageClient;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;

/**
 * @author CHENCHEN
 * @company 北京学佳澳教育科技
 * @create 2023-03-22 12:49
 */
@Slf4j
@Component
public class FastDFSUtil {

    private final AppendFileStorageClient appendFileStorageClient;
    private final FastFileStorageClient fastFileStorageClient;

    public FastDFSUtil(AppendFileStorageClient appendFileStorageClient, FastFileStorageClient fastFileStorageClient) {
        this.appendFileStorageClient = appendFileStorageClient;
        this.fastFileStorageClient = fastFileStorageClient;
    }

    public StorePath uploadAppenderFile(MultipartFile file, String group) throws IOException {
        String fileType = FileUtil.getFileType(file);
        return appendFileStorageClient.uploadAppenderFile(group, file.getInputStream(), file.getSize(), fileType);
    }

    public void modifyFile(String group, String filePath, MultipartFile file, long fileOffset) throws IOException {
        appendFileStorageClient.modifyFile(group, filePath, file.getInputStream(), file.getSize(), fileOffset);
    }

    public String uploadFile(MultipartFile file, Set<MetaData> metaData) throws IOException {
        String fileType = FileUtil.getFileType(file);
        StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), fileType, metaData);
        return storePath.getPath();
    }

    public StorePath uploadEmptyFile(String group) throws IOException {
        byte[] emptyBytes = new byte[0];
        InputStream emptyInputStream = new ByteArrayInputStream(emptyBytes);
        StorePath storePath = fastFileStorageClient.uploadFile(group, emptyInputStream, 0, null);
        return storePath;
    }

    public StorePath uploadAppendFile(MultipartFile file, String group) throws Exception {
        String fileType = FileUtil.getFileType(file);
        StorePath storePath = appendFileStorageClient.uploadAppenderFile(group, file.getInputStream(), file.getSize(), fileType);
        return storePath;
    }

    public void deleteFile(String filePath) {
        fastFileStorageClient.deleteFile(filePath);
    }

}
